package com.it.tydic.estate.common.oauth;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.it.tydic.estate.common.aop.CodeMsg;
import com.it.tydic.estate.common.aop.Result;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*@Configuration*/
public class CustomAuthExceptionHandler implements AuthenticationEntryPoint, AccessDeniedHandler {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Throwable cause = authException.getCause();
        String tokenStr = "";
        if (cause instanceof InvalidTokenException) {
            handleExceprion(response, "invalid_token");
        } else {
            handleExceprion(response, "no_nuthen");
        }

    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        handleExceprion(response, "no_nuthen");
    }

    public void handleExceprion(HttpServletResponse response, String tokenStr) throws IOException {

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.addHeader("Access-Control-Max-Age", "1800");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out=response.getWriter();
        ObjectMapper objectMapper=new ObjectMapper();
        if ("invalid_token".equals(tokenStr)) {
            out.write(objectMapper.writeValueAsString(Result.error(CodeMsg.INVALID_TOKEN)));
        } else {
            out.write(objectMapper.writeValueAsString(Result.error(CodeMsg.NO_NUTHEN)));
        }
        out.flush();
        out.close();
    }

}
